package com.csw.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo15Pi {
  def main(args: Array[String]): Unit = {

    //1、生成一个大集合
    val list: Seq[Int] = 0 to 100000000

    val conf = new SparkConf()
      .setMaster("local")
      .setAppName("Pi")
    val sc: SparkContext = new SparkContext(conf)

    //2、将集合转换成rdd
    val dataRDD: RDD[Int] = sc.parallelize(list)

    //3、在正方形内随机生成点
    val pointRDD: RDD[(Double, Double)] = dataRDD.map(i => {
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1
      (x, y)
    })

    //    pointRDD.foreach(println)

    //4、取出圆内的点
    val filterRDD: RDD[(Double, Double)] = pointRDD.filter(kv => {
      kv._1 * kv._1 + kv._2 * kv._2 < 1
    })

    //5、通过公式计算圆周率
    val pi: Double = filterRDD.count().toDouble / dataRDD.count() * 4

    println("pi="+pi)
  }

}
